package com.start.core.aspects;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.start.common.api.Result;
import com.start.common.dataImport.ExcelActionType;
import com.start.common.dic.DictMapperParams;
import com.start.common.dic.DictMapperParamsUtils;
import com.start.common.dic.StartBaseDicMapperHandler;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Aspect
@Component
public class DicDataAspect {
    @Pointcut("execution(public * com.start.*.controller.*(..))||@annotation(com.start.common.dic.HandlerDic)")
    public void dicMapperPointcut() {
    }

    @Around("dicMapperPointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object resultObj = point.proceed();
        if (resultObj == null) return resultObj;
        if (!(resultObj instanceof Result)) {
            return resultObj;
        }
        Result result = (Result) resultObj;
        Object data = result.getData();
        if (data == null) return resultObj;
        if (!(data instanceof IPage)) {
            return resultObj;
        }
        List<?> records = ((IPage<?>) data).getRecords();
        if (records.isEmpty()) return resultObj;
        DictMapperParams dictMapperParams = DictMapperParamsUtils.getExcelMapperParams(records.get(0).getClass(), ExcelActionType.EXCEL_EXPORT);
        Map<String, StartBaseDicMapperHandler> handlerFiled = dictMapperParams.getHandlerFiled();
        if (handlerFiled == null || handlerFiled.isEmpty()) {
            return resultObj;
        }

        List<JSONObject> resultData = new ArrayList<>();
        Set<String> keySet = handlerFiled.keySet();
        for (int i = 0; i < records.size(); i++) {
            Object record = records.get(i);
            JSONObject item = JSONObject.parseObject(JSONObject.toJSONString(record));
            for (String key : keySet) {
                if (!item.containsKey(key)) continue;
                StartBaseDicMapperHandler entityDictMapperHandler = handlerFiled.get(key);
                String value = entityDictMapperHandler.getExportValue(item.get(key));
                item.put(key + "_dic_label", value);
            }
        }
        IPage<?> srcPage = ((IPage<?>) data);
        IPage page = new Page();
        page.setPages(srcPage.getPages());
        page.setCurrent(srcPage.getCurrent());
        page.setTotal(srcPage.getTotal());
        page.setSize(srcPage.getSize());
        page.setRecords(resultData);
        result.setData(page);
        return result;

    }


}
